<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\CouponItem;
use App\Models\CouponOrder;
use App\Models\CouponShop;
use App\Models\CouponExtract;
use App\Models\CouponShopIncome;
use App\Models\MealUserCard;
use App\Models\System;
use App\Services\OSS;
use DB;

class CouponController extends Controller
{
    //
    public function release()
    {
    	return view('coupon.add');
    }

    /**
     * 授权商户
     */
    public function authShop(Request $request)
    {
        $params['appid'] = env('WXAPPID');
        $params['secret'] = env('WXSECRET');
        $params['js_code'] = $request->input('code');
        $wxname = $request->input('wxname');
        $avatar = $request->input('avatar');
        $params['grant_type'] = 'authorization_code';
        $param_str = http_build_query($params);
        $result = json_decode($this->getCurl("https://api.weixin.qq.com/sns/jscode2session?".$param_str),true);
        $result['code'] = $params['js_code'];
        $shop = new CouponShop;
        $shopInfo = $shop->where('openid',$result['openid'])->first();
        $insertData = ['shop_name'=>$wxname,'avatar'=>$avatar,'openid'=>$result['openid']];
        $res = $shop->auth($insertData,$result['openid']);
        if(!$res['success']){
            return response()->json($res);
        }
        return response()->json(['success'=>true,'code'=>'000','message'=>'获取成功','data'=>$result,'info'=>$res['data']]);
    }

    /**
     * 解密用户手机号
     */
    public function dePhone(Request $request)
    {
        require app_path("Common/wxphone/wxBizDataCrypt.php");
        $shop = new CouponShop;
        $appid = env('WXAPPID');//小程序APPID
        $sessionKey = $request->input('session_key');
        $iv = $request->input('iv');
        $encryptedData = $request->input('encryptedData');
        $position = (int)$request->input('position',2);

        $pc = new \WXBizDataCrypt($appid, $sessionKey);
        $errCode = $pc->decryptData($encryptedData, $iv, $data);
        $shop = $shop->where('openid',$request->input('openid'))->first();
        $shop->tel = json_decode($data,true)['phoneNumber'];
        $shop->position = $position;
        if($shop->save()){
            return response()->json(['success'=>true,'code'=>'000','message'=>'完成','data'=>$data,'info'=>[
                'avatar'=>$shop->avatar,
                'tel'=>$shop->tel,
                'position'=>$shop->position,
            ]]);
        }else{
            return response()->json(['success'=>true,'code'=>'000','message'=>'解密出错，请稍后再试！']);
        }
    }
    /**
     * 修改昵称
     */
    public function editShopName(Request $request)
    {
        $name = $request->input('name',false);
        $shopId = $request->input('shop_id');
        $shop = new CouponShop;
        $shopInfo = $shop->where('id',$shopId)->first();
        $shopInfo->shop_name = $name;
        if($shopInfo->save()){
            return response()->json([
                'success'=>true,
                'code'=>'000',
                'message'=>'修改成功！'
            ]);
        }else{
            return response()->json([
                'success'=>false,
                'code'=>'006',
                'message'=>'修改失败，请稍后重试！'
            ]);
        }
    }

    /**
     * 商户信息
     */
    public function shopInfo(Request $request)
    {
        $shopid = $request->input('shop_id');
        $shopinfo = CouponShop::where('id',$shopid)->first();
        if($shopinfo->position == 2){
            $shopinfo = CouponShop::where('id',$shopinfo->clerk_shop_id)->first() ;
            $shopname = $shopinfo->shop_name ?? '未授权';
            $shopid = $shopinfo->id;
        }else{
            $shopname = $shopinfo->shop_name;
            $shopid = $shopinfo->id;
        }
        return response()->json([
            'success'=>true,
            'code'=>'000',
            'message'=>'查询完成',
            'name'=>$shopname,
            'id'=>$shopid,
            'amount'=>$shopinfo->amount,
        ]);
    }

    /**
     * 发布优惠券
     */
    public function doRelease(Request $request)
    {
    	$post = $request->only([
    		'starttime','coupon_name','price','stoptime','centerBackground','num','address','desc','cost_price','lng','lat','province','city','is_mail','benefit_price','benefit'
    	]);
        if($post['cost_price']>$post['price']){
            return response()->json([
                'success'=>false,
                'code'=>"004",
                'message'=>'成本价不能大于出售价格',
            ]);
        }
        $shopName = $request->input('shop_name');
        $coupon = new CouponItem;
    	$shop = new CouponShop;
        $shopInfo = $shop->where('shop_name',$shopName)->first();
        if(!$shopInfo){
            return response()->json([
                'success'=>false,
                'code'=>"004",
                'message'=>'店铺不存在',
            ]);
        }
        $post['shop_id'] = $shopInfo->id;
    	return response()->json($coupon->add($post));
    }

    /**
     * 列表查询
     */
    public function list(Request $request)
    {
        $item = $request->input('item',10);
        $lng = $request->input('lng',0);
        $lat = $request->input('lat',0);
    	$city = $request->input('city',false);
        $w[] = ["valid",'=',1];
        if($city){
            // $w[] = ["city",'=',$city];
        }
    	$coupon = new CouponItem;
    	$data = $coupon
        ->select(DB::raw('*,(POWER(MOD(ABS(lng - '.$lng.'),360),2) + POWER(ABS(lat - '.$lat.'),2)) AS distance,null as coupon_distance,'.$lng.' as lng2,'.$lat.' as lat2'))
        ->where($w)
        ->orderBy('distance','asc')
        ->paginate($item);
    	return response()->json([
    		'success'=>true,
    		'code'=>"000",
    		'message'=>'查询成功',
    		'data'=>$data,
    	]);
    }

    /**
     * 订单
     */
    public function orderList(Request $request)
    {
    	$item = $request->input('item',10);
    	$status = $request->input('status',1);
    	$user_id = $request->input('user_id');
    	$order = new CouponOrder;
        $w = [];
        $w[] = ['lexiang_coupon_order.pay_state','=',1];
        $w[] = ['lexiang_coupon_order.user_id','=',$user_id];
        if($status==2){
            $w[] = ['lexiang_coupon_order.douse','=',1 ];
        }
    	$data = $order
    	->join('lexiang_coupon_item as lci','lci.id','=','lexiang_coupon_order.coupon_id')
    	->where($w)
    	->select("lexiang_coupon_order.*",'lci.coupon_name','lci.address','lci.price','lci.over_time')
        ->orderBy('lexiang_coupon_order.created_at','desc')
    	->paginate($item);

    	return response()->json([
    		'success'=>true,
    		'code'=>"000",
    		'message'=>'查询成功',
    		'data'=>$data,
    	]);
    }

    /**
     * 订单详情
     */
    public function orderDetail(Request $request)
    {
        $orderid = $request->input('orderid');
        // 1 已购买  2 已使用
        $status = $request->input('status',1);
        $order = new CouponOrder;
        $w = [];
        $w[] = ['lexiang_coupon_order.id','=',$orderid];
        $orderinfo = $order
        ->join('lexiang_coupon_item as lci','lci.id','=','lexiang_coupon_order.coupon_id')
        ->where($w)
        ->select("lexiang_coupon_order.*",'lci.coupon_name','lci.address','lci.price','lci.over_time','lci.start_time')
        ->first();
        return response()->json([
            'success'=>true,
            'code'=>"000",
            'message'=>'查询成功',
            'data'=>$orderinfo,
        ]);
    }

    /**
     * 详情
     */
    public function details(Request $request)
    {
    	$coupon = new CouponItem;
    	$couponInfo = $coupon->where('id',$request->input('coupon_id'))->select(DB::raw('*,null as sell'))->first();
    	return response()->json(['success'=>true,'code'=>'000','message'=>'查询完成','data'=>$couponInfo]);
    }

    /**
     * 卡券管理
     */
    public function manageCoupon(Request $request)
    {
    	$coupon = new CouponItem;
    	$data = $coupon
        ->leftJoin('lexiang_coupon_shop as lcs','lcs.id','=','lexiang_coupon_item.shop_id')
        ->where(function($q)use($request){
            if($request->has('city')){
                return $q->where('lexiang_coupon_item.city',$request->input('city'));
            }
            if($request->has('province')){
                return $q->where('lexiang_coupon_item.province',$request->input('province'));
            }
            if($request->has('shop_name')){
                return $q->where('lcs.shop_name','like',"%".$request->input('shop_name').'%');
            }
        })
        ->where('lexiang_coupon_item.valid','>',-1)
        ->select('lexiang_coupon_item.*','lcs.shop_name')
        ->paginate();
        $citys = $coupon->groupBy('city')->pluck('city');
        $provinces = $coupon->groupBy('province')->pluck('province');
    	return view('coupon.manage',['coupons'=>$data,'citys'=>$citys,'provinces'=>$provinces]);
    }

    /**
     * 卡券详情
     */
    public function couponDetail(Request $request)
    {
    	$coupon = new CouponItem;
    	$data = $coupon->where('id',$request->input('coupon_id'))->first();
    	if($data){
    		return response()->json([
	    		'success'=>true,
	    		'code'=>'000',
	    		'message'=>'查询完成',
	    		'data'=>$data
	    	]);
    	}else{
    		return response()->json([
	    		'success'=>false,
	    		'code'=>'003',
	    		'message'=>'查询出错',
	    		'data'=>$data
	    	]);
    	}
    	
    }

    /**
     * 上传图片
     */
    public function upload(Request $request)
    {
    	$file = $request->file('images');
        $fileExt = ltrim($file->getClientOriginalExtension(),'.');
        $fileName = 'CouponDescImgs/'.md5(uniqid(microtime(true),true)).'.'.$fileExt;
        $upRes = OSS::publicUpload(config('aliyun.BucketName'),$fileName,$file);
        return response()->json([
        	'errno'=>0,
        	'data'=>[
        		"https://jiashilexiang.oss-cn-beijing.aliyuncs.com/".$fileName
        	]
        ]);
    }

    /**
     * 商户订单
     */
    public function shopOrderList(Request $request)
    {
        // 1已核销。2出售待核销。3今日出售
        $status = $request->input('status');
        $shopId = $request->input('shop_id');
        $order = new CouponOrder;
        if($status==1){
            $orders = $order
            ->join('lexiang_coupon_item as lci','lci.id','=','lexiang_coupon_order.coupon_id')
            ->join('lexiang_coupon_shop as lcs','lcs.id','=','lci.shop_id')
            ->where('lci.shop_id',$shopId)
            ->where('lexiang_coupon_order.pay_state',1)
            ->where('lexiang_coupon_order.douse',1)
            ->select('lexiang_coupon_order.*','lci.coupon_name','lcs.shop_name')
            ->orderBy('created_at','desc')
            ->paginate(15);
        }

        if($status==2){
            $orders = $order
            ->join('lexiang_coupon_item as lci','lci.id','=','lexiang_coupon_order.coupon_id')
            ->join('lexiang_coupon_shop as lcs','lcs.id','=','lci.shop_id')
            ->where('lci.shop_id',$shopId)
            ->where('lexiang_coupon_order.pay_state',1)
            ->where('lexiang_coupon_order.douse',0)
            ->select('lexiang_coupon_order.*','lci.coupon_name','lcs.shop_name')
            ->orderBy('created_at','desc')
            ->paginate(15);
        }

        if($status==3){
            $startTime = strtotime(date('Ymd 00:00:00'));
            $endTime = strtotime(date('Ymd 23:59:59'));
            $orders = $order
            ->join('lexiang_coupon_item as lci','lci.id','=','lexiang_coupon_order.coupon_id')
            ->join('lexiang_coupon_shop as lcs','lcs.id','=','lci.shop_id')
            ->where('lci.shop_id',$shopId)
            ->where('lexiang_coupon_order.pay_state',1)
            ->whereBetween('lexiang_coupon_order.created_at',[$startTime,$endTime])
            ->select('lexiang_coupon_order.*','lci.coupon_name','lcs.shop_name')
            ->orderBy('created_at','desc')
            ->paginate(15);
        }

        return response()->json([
            'success'=>false,
            'code'=>'000',
            'message'=>'查询完成',
            'data'=>$orders
        ]);
    }

    /**
     * 下单
     */
    public function order(Request $request)
    {
    	require(base_path('app/Packages/weixinpay/').'WeixinPay.php');
    	$order = new CouponOrder;
    	$couponInfo = CouponItem::where('id',$request->input('coupon_id'))->first();
        $userid = $request->input('user_id');
        $useCard = MealUserCard::where('card_invalid',1)->where('users_id',$userid)->exists();
        $price = $couponInfo->price;
        if($useCard && $couponInfo->benefit == 0){
            $price = $couponInfo->benefit_price;
        }
    	if($couponInfo->num <= 0){
    		return response()->json([
    			'success'=>false,
    			'code'=>'004',
    			"message"=>'非常抱歉，这个卡券买完了！',
    		]);
    	}
        if($couponInfo->price <= 0){
            return response()->json([
                'success'=>false,
                'code'=>'004',  
                "message"=>'当前卡券暂不出售',
            ]);
        }
    	$data = [
    		'total'=>$price,
    		'user_id'=>$request->input('user_id'),
    		'openid'=>$request->input('openid'),
    		'coupon_id'=>$request->input('coupon_id'),
    	];
    	$res = $order->add($data);
    	if(!$res['success']){
    		return response()->json($res);
    	}
    	$wx = new \Wxpayandroid;
        $backurl = "http://console.jiashilexiang.cn/api/coupon/notifyurl/";
    	return response()->json($wx->WeixinpayXcx($price,$res['data']['order_number'],"嘉时乐享 - 优惠券",$request->input('openid'),$backurl));
    }

    /**
     * 扫一扫
     */
    public function useSys(Request $request)
    {
        $orderid = $request->input('orderid');
        $shopId = $request->input('shop_id');
        $order = new CouponOrder;
        $coupon = new CouponItem;
        $shop = new CouponShopIncome;
        $orderInfo = $order->where([
            ['id','=',$orderid],
        ])->orWhere([
            ['order_number','=',$orderid],
        ])->first();
        $shopinfo = CouponShop::where('id',$shopId)->first();
        if($shopinfo->position == 2){
            $shopId = $shopinfo->clerk_shop_id;
        }
        if(!$orderInfo){
            return response()->json([
                'success'=>false,
                'code'=>'004',
                'message'=>"没查询到该卡券的信息"
            ]);
        }
        $couponInfo = $coupon->where('id',$orderInfo->coupon_id)->first();
        if($orderInfo->pay_state!=1){
            return response()->json([
                'success'=>false,
                'code'=>'004',
                'message'=>"卡券还未支付"
            ]);
        }
        if($shopId!=$couponInfo->shop_id){
            return response()->json([
                'success'=>false,
                'code'=>'004',
                'message'=>"卡券不属于本商户"
            ]);
        }
        if($orderInfo->douse==1){
            return response()->json([
                'success'=>false,
                'code'=>'004',
                'message'=>"此卡券已经使用过了"
            ]);
        }
        if($couponInfo->getOriginal('start_time')>time() || $couponInfo->getOriginal('over_time')<time()){
            return response()->json([
                'success'=>false,
                'code'=>'004',
                'message'=>"卡券已过期"
            ]);
        }
        $orderInfo->douse = 1;
        $orderInfo->use_at = time();
        $res = $shop->add(['shop_id'=>$couponInfo->shop_id,'coupon_id'=>$couponInfo->id,'money'=>$couponInfo->cost_price]);
        if(!$res['success']){
            return response()->json($res);
        }
        if($orderInfo->save()){
            return response()->json([
                'success'=>true,
                'code'=>'000',
                'message'=>'已核销',
                'amount'=>$res['amount']
            ]);
        }else{
            return response()->json([
                'success'=>false,
                'code'=>'006',
                'message'=>'核销出错，请稍后再试',
            ]);
        }
    }

    /**
     * 店铺列表
     */
    public function shoplist(Request $request)
    {
        $shop = new CouponShop;
        $shops = $shop
        ->select(DB::raw('*,null as address'))
        ->orderBy('created_at','desc')
        ->paginate($request->input('item',10));
        return view('coupon.shop',['shops'=>$shops]);
    }

    /**
     * 已发布店铺列表
     */
    public function fabushoplist(Request $request)
    {
        $shop = new CouponShop;
        $shops = $shop->join('lexiang_coupon_item as lci','lci.shop_id','=','lexiang_coupon_shop.id')
        ->select(DB::raw('lexiang_coupon_shop.*,null as address'))
        ->orderBy('lexiang_coupon_shop.created_at','desc')
        ->groupBy('lci.shop_id')
        ->paginate($request->input('item',10));
        return view('coupon.shopfabulist',['shops'=>$shops]);
    }

    /**
     * 店铺详情
     */
    public function shopDetail(Request $request)
    {
        $shop = new CouponShop;
        $shops = $shop
        ->where('id',$request->input('shop_id'))
        ->select(DB::raw('*,null as address,null as ordertotal,null as sell,null as extract_money'))
        ->first();
        return view('coupon.shopdetail',['shop'=>$shops]);
    }

    /**
     * 回调函数
     */
    public function notifyurl(Request $request)
    {
    	$nowtime = time();
        $xml = isset($GLOBALS['HTTP_RAW_POST_DATA']) ? $GLOBALS['HTTP_RAW_POST_DATA'] : file_get_contents("php://input");
        // file_put_contents(base_path('storage/logs/').'wxpay.log', $xml."\n---------\n", FILE_APPEND);
        // 将服务器返回的XML数据转化为数组
        // 将XML转为array
        // 禁止引用外部xml实体
        libxml_disable_entity_loader(true);
        $data = json_decode(json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
        file_put_contents(base_path('storage/logs/').'wxpay.log', json_encode($data)."\n---------\n", FILE_APPEND);
        $order = new CouponOrder;
        $coupon = new CouponItem;
        $orderInfo = $order->where([
        	['order_number','=',$data['out_trade_no']],
        ])->first();
        if($orderInfo->pay_state == 1){
        	echo 'success';die;
        }
        $coupon = $coupon->where('id',$orderInfo->coupon_id)->first();
        if($data['result_code']!='SUCCESS'){
        	echo 'fail';die;
        }
        $coupon->num = $coupon->num-1;
        $orderInfo->pay_state = 1;
        $orderInfo->dopay_at = $nowtime;
        $coupon->save();
        if($orderInfo->save()){
        	echo 'success';die;
        }else{
        	echo 'fail';die;
        }
    }

    /**
     * 卡券购买列表
     */
    public function buyList(Request $request)
    {
    	$item = $request->input('item',10);
    	$state = $request->input('pay_state',false);
    	$order = new CouponOrder;
    	$data = $order
    	->join('lexiang_coupon_item','lexiang_coupon_item.id','=','lexiang_coupon_order.coupon_id')
    	->where(function($q)use($state){
    		if($state!==false){
    			return $q->where([
    		    		["lexiang_coupon_order.pay_state",'=',$state],
    		    	]);
    		}
    	})
    	->select(DB::raw('lexiang_coupon_order.*,lexiang_coupon_item.coupon_name,lexiang_coupon_item.address,lexiang_coupon_item.price,lexiang_coupon_item.over_time,null as nickname,null as pay_state_text'))
        ->orderBy('lexiang_coupon_order.created_at','desc')
    	->paginate($item);
    	return view('coupon.order',['orders'=>$data]);
    }

    /**
     * 提现申请
     */
    public function propose(Request $request)
    {
        $data = $request->only([
            'shop_id','amount','bank_number','bank_open','bank_name','bank_tel'
        ]);

        $extract = new CouponExtract;
        return response()->json($extract->add($data));
    }

    /**
     * 修改卡券
     */
    public function editCoupon(Request $request)
    {
        $couponId = $request->input('coupon_id');
        $data = [
            'coupon_desc'=>$request->input('desc'),
            'coupon_name'=>$request->input('coupon_name'),
            'start_time'=>strtotime($request->input('starttime')),
            'over_time'=>strtotime($request->input('stoptime')),
            'num'=>$request->input('num'),
            'lng'=>$request->input('lng'),
            'lat'=>$request->input('lat'),
            'price'=>$request->input('price'),
            'province'=>$request->input('province'),
            'city'=>$request->input('city'),
            'cost_price'=>$request->input('cost_price'),
            'address'=>$request->input('address'),
            'valid'=>$request->input('cardstatus'),
        ];
        if($request->hasFile('mealcardBackground')){
            $file = $request->file('mealcardBackground');
            $fileExt = ltrim($file->getClientOriginalExtension(),'.');
            $filename = 'CouponCover/'.md5(uniqid(microtime(true),true)).'.'.$fileExt;
            OSS::publicUpload(config('aliyun.BucketName'),$filename,$file);
            $data['cover_img'] = $filename;
        }
        $coupon = new CouponItem;
        return response()->json($coupon->edit($couponId,$data));
    }

    private function postCurl($url,$post_data) {
        //初始化
        $curl = curl_init();
        //设置抓取的url
        curl_setopt($curl, CURLOPT_URL, $url);
        //设置头文件的信息作为数据流输出
        curl_setopt($curl, CURLOPT_HEADER, 1);
        //设置获取的信息以文件流的形式返回，而不是直接输出。
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        //设置post方式提交
        curl_setopt($curl, CURLOPT_POST, 1);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $post_data);
        //执行命令
        $data = curl_exec($curl);
        //关闭URL请求
        curl_close($curl);
        //显示获得的数据
        return $data;
    }

    private function getCurl($url) {
        //初始化
        $curl = curl_init();
        //设置抓取的url
        curl_setopt($curl, CURLOPT_URL, $url);
        //设置头文件的信息作为数据流输出
        // curl_setopt($curl, CURLOPT_HEADER, 1);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        //设置获取的信息以文件流的形式返回，而不是直接输出。
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        //执行命令
        $data = curl_exec($curl);
        //关闭URL请求
        curl_close($curl);
        //显示获得的数据
        return $data;
    }

    /**
     * 提现查询
     */
    public function extractLog(Request $request)
    {
        $shopId = $request->input('shop_id');

        $extract = new CouponExtract;
        $data = $extract->where('coupon_shop_id',$shopId)->orderBy('created_at','desc')->first();
        if($data){
            return response()->json([
                'success'=>true,
                'code'=>'000',
                'message'=>"查询成功",
                'data'=>$data
            ]);
        }else{
            return response()->json([
                'success'=>false,
                'code'=>'000',
                'message'=>"没有记录",
            ]);
        }
        
    }

    /**
     * 提现申请列表
     */
    public function extractList(Request $request)
    {
        $extract = new CouponExtract;
        $exdata = $extract
        ->join('lexiang_coupon_shop as lcs','lcs.id','=','lexiang_coupon_extract.coupon_shop_id')
        ->select('lexiang_coupon_extract.*','lcs.shop_name','lcs.id as shop_id')
        ->paginate(15);
        $status_de = ['1'=>'待审','2'=>'通过申请','3'=>'已打款','4'=>'已驳回'];
        return view('coupon.extract',['exdata'=>$exdata,'status_de'=>$status_de]);
    }

    /**
     * 提现处理操作
     */
    public function extractAction(Request $request)
    {
        $nowtime = time();

        $post = $request->only(['action','extractid','extract_desc']);

        if(empty($post['extractid'])) return response()->json(['success'=>false,'code'=>'1','message'=>'提现ID不能为空']);

        $action_de = ['YCL'=>3,'BH'=>4,'KS'=>2];

        $extract = CouponExtract::find($post['extractid']);

        if(!$extract) return response()->json(['success'=>false,'code'=>'1','message'=>'未查询到']);

        switch ($post['action']) {
            case 'YCL':// 已打款
                $extract->extract_status = $action_de[$post['action']];
                break;
            case 'BH':// 驳回
                $extract->extract_status = $action_de[$post['action']];
                if(empty($post['extract_desc'])){
                    return response()->json(['success'=>false,'code'=>'1','message'=>'请填写理由']);
                }
                $extract->extract_explain = $post['extract_desc'];
                break;
            case 'KS':// 开始处理
                $extract->extract_status = $action_de[$post['action']];
                break;
        }

        $result = $extract->save();

        if($result){
            return response()->json(['success'=>true,'code'=>0,'message'=>'修改成功！']);
        }else{
            return response()->json(['success'=>false,'code'=>'2','message'=>'修改失败，请稍后重试！']);
        }
    }

    public function test(Request $request){
        $f = file_get_contents('https://jiashilexiang.oss-cn-beijing.aliyuncs.com/APP/HomeJson/city.json');
        dd(json_decode($f,true));
    }

    /**
     * 搜索员工手机号
     */
    public function searchStaff(Request $request)
    {
        $staff = CouponShop::where('tel',$request->input('tel'))->first();
        if($staff){
            return response()->json([
                'success'=>true,
                'code'=>'000',
                'message'=>'查询完成',
                'data'=>$staff
            ]);
        }else{
            return response()->json([
                'success'=>false,
                'code'=>'003',
                'message'=>'没有这个用户',
                'data'=>[]
            ]);
        }
    }

    /**
     * 设置员工
     */
    public function setStaff(Request $request)
    {
        $shopid = $request->input('shop_id');
        $userid = $request->input('user_id');
        $staff = CouponShop::where('id',$userid)->first();
        $staff->position = 2;
        $staff->clerk_shop_id = $shopid;
        if($staff->save()){
            return  response()->json([ 
                'success'=>true,
                'code'=>"000",
                'message'=>'修改成功'
            ]);
        }else{
            return response()->json([
                'success'=>false,
                'code'=>'003',
                'message'=>"服务器出错，请稍后再试！"
            ]);
        }
    }

    /**
     * 隶属员工
     */
    public function staffs(Request $request)
    {
        $shopid = $request->input('shop_id');

        $staffs = CouponShop::where([
            ['clerk_shop_id','=',$shopid],
            ['position','=',2],
        ])
        ->selectRaw('id as name,shop_name as value,avatar,null as shows')
        ->get();

        if($staffs){
            return response()->json([
                'success'=>true,
                'code'=>'000',
                'message'=>'搜索成功',
                'data'=>$staffs
            ]);    
        }else{
            return response()->json([
                'success'=>false,
                'code'=>"003",
                'message'=>"没有隶属员工",
                'data'=>[]
            ]);
        }
    }

    /**
     * 删除员工
     */
    public function delStaff(Request $request)
    {
        $shopid = $request->input('shop_id');
        $staffid = $request->input('staff_id');

        $staffInfo = CouponShop::where('id',$staffid)->first();

        $staffInfo->clerk_shop_id = 0;

        if($staffInfo->save()){
            return response()->json([
                'success'=>true,
                'code'=>'000',
                'message'=>'删除成功',
            ]);
        }else{
            return response()->json([
                'success'=>false,
                'code'=>'003',
                'message'=>'删除出错，请稍后再试',
            ]);
        }
    }

    /**
     * 删除卡券
     */
    public function delCoupon(Request $request)
    {
        $couponid = $request->input('couponid');
        $couponinfo = CouponItem::where('id',$couponid)->first();

        $couponinfo->valid = -1;

        if($couponinfo->save()){
            return response()->json([
                'success'=>true,
                'code'=>'000',
                'message'=>'已删除'
            ]);
        }else{
            return response()->json([
                'success'=>false,
                'code'=>'003',
                'message'=>'已删除或不存在'
            ]);
        }
    }
}
